import java.io.IOException;
import java.net.*;

public class UDPMyEchoServer 
{
	/**
	 * @param args The value inputted as argument will be used as the Server's Port Number.
	 * @throws Exception Exception required when using DatagramSocket
	 * @author Chang Hyun Park
	 */
	public static void main(String[] args)
	{
		byte[] recvData;
		byte[] sendData;
		int portNumber;
		
		if(args.length!=0)
		{
			portNumber = Integer.parseInt(args[0]);
		}
		else
		{
			portNumber = 64777;	//Default Port number
		}
		
		try
		{
			DatagramSocket serverSocket = new DatagramSocket(portNumber);	//Create Socket
			
			InetAddress thisIP = InetAddress.getLocalHost();	//Get Local Host's IP address
			int thisPort = serverSocket.getLocalPort();	//Get Local Host's Port number
			System.out.println("(1)   This Server's IP address:Port is "+thisIP.toString()+":"+thisPort+".");
			//Find the Server's Local Address
			
			while(true)
			{
				recvData = new byte[1024];
				sendData = new byte[1024];
				
				DatagramPacket recvPacket = new DatagramPacket(recvData, recvData.length);
				serverSocket.receive(recvPacket);//Receive packet from client
				InetAddress clientIP = recvPacket.getAddress();
				int clientPort = recvPacket.getPort();
				String buffer = new String(recvPacket.getData());
				System.out.println("(2)   ["+clientIP.toString().substring(1)+":"+clientPort+"] Says: "+buffer);
				//Find the client's IP, Port from the datagram Packet
				
				//echo String buffer back to client
				DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIP, clientPort);
				sendPacket.setData(buffer.getBytes());
				serverSocket.send(sendPacket);
			}
		}
		catch(SocketException e)
		{
			System.out.println(e);
		}
		catch(IOException e)
		{
			System.out.println(e);
		}
	}
}
